import Vue from 'vue'
import VueRouter from 'vue-router'
import { getItem } from '@/utils/storage.js'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    hidden: true,
    redirect: '/admin/home'
  },
  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },
  {
    path: '/login',
    name: 'Login',
    hidden: true,
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('@/components/layout/index'),
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/Home.vue')
      },
      {
        path: 'bloglist',
        name: 'bloglist',
        component: () => import('@/views/blog/Blog.vue')
      },
      {
        path: 'blogcontent',
        name: 'blogcontent',
        component: () => import('@/components/blog/BlogContent.vue')
      },
      {
        path: 'blogcontent/:id',
        name: 'blogcontent',
        component: () => import('@/components/blog/BlogContent.vue')
      },
      {
        path: 'notelist',
        name: 'notelist',
        component: () => import('@/views/note/Note.vue')
      },
      {
        path: 'notecontent',
        name: 'notecontent',
        component: () => import('@/components/note/noteContent.vue')
      },
      {
        path: 'notecontent/:id',
        name: 'notecontent',
        component: () => import('@/components/note/noteContent.vue')
      },
      {
        path: 'resources',
        name: 'Resourses',
        component: () => import('@/views/resourse/Resourse.vue')
      }
    ]
  },
  { path: '*', redirect: '/404', hidden: true }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => err)
}
router.beforeEach((to, form, next) => {
  // to 要访问的路由
  // from 上一个路由
  // next 想要继续访问的路由
  const reg = /^\/admin\/*/
  const userInfo = getItem('userInfo')
  if (reg.test(to.path)) {
    // 判断用户是否登录
    if (userInfo) {
      next()
    } else {
      alert('您未登录,请先登录')
      next('/login')
    }
  } else {
    next()
  }
  // 如果访问不是管理页面 就可以继续访问
  next()
})
export default router
